Laravel 提供強大的 File Storage API,讓我們可以輕鬆地與本地或遠端的檔案系統互動。
Laravel 內建支援多種儲存驅動,例如:local、public、s3、sftp 等。
use Illuminate\Support\Facades\Storage;
Storage::disk('local')->put('example.txt', 'Contents');
這行指令會將 example.txt
寫入至 storage/app/example.txt
。
使用 SFTP 存取遠端檔案
你也可以透過 SFTP 存取遠端主機的檔案。
在 disks 陣列中新增一個 sftp 設定:
'disks' => [
// ... 其他 disks
'sftp' => [
'driver' => 'sftp',
'host' => env('SFTP_HOST'),
'username' => env('SFTP_USERNAME'),
'password' => env('SFTP_PASSWORD'),
'port' => (int) env('SFTP_PORT', 22),
'timeout' => 30,
],
],
建議使用 .env
管理敏感資訊。
use Illuminate\Support\Facades\Storage;
$folderPath = 'your/folder/path'; // SFTP 上的資料夾路徑
$files = Storage::disk('sftp')->files($folderPath);
如果你想使用 PhpSpreadsheet 載入其中一個 Excel 檔案:
use PhpOffice\PhpSpreadsheet\IOFactory;
$path = $files[0]; // 取第一個檔案
$tempPath = storage_path('app/temp.xlsx'); // 下載檔案至本地暫存目錄
// 使用 PhpSpreadsheet 載入檔案
Storage::disk('local')->put(
'temp.xlsx',
Storage::disk('sftp')->get($path)
);
$reader = IOFactory::createReaderForFile($tempPath);
$spreadsheet = $reader->load($tempPath);